package com.hafu.dao;

import com.hafu.model.KuCun;
import com.hafu.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class KuCunDao {

    public ArrayList<KuCun> getKuCunList() {
        ArrayList<KuCun> list = new ArrayList<>();
        Connection conn = null;
        try {
            conn = DbUtil.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String sql = "SELECT * FROM kucun";

        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String SpName = resultSet.getString("spname");
                int num = resultSet.getInt("num");
                KuCun kuCun1 = new KuCun(id, SpName, num);
                list.add(kuCun1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return list;
    }

    public KuCun getKuCunBySpName(String spName, Connection conn) throws SQLException {
        String sql = "SELECT * FROM kucun WHERE spname = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, spName);
        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("spname");
            int num = resultSet.getInt("num");
            KuCun kuCun = new KuCun(id, name, num);
            return kuCun;
        }
        return null;
    }

    public boolean addKuCun(KuCun kuCun, Connection conn) throws SQLException {
        String sql = "INSERT INTO kucun(spname, num) VALUES (?, ?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, kuCun.getSpName());
        preparedStatement.setInt(2, kuCun.getNum()); // Fixed spelling mistake (lnt -> int)

        int i = preparedStatement.executeUpdate();
        return i > 0;
    }

    public boolean updateKuCun(KuCun kuCunBySpName, Connection conn) throws SQLException {
        String sql = "UPDATE kucun SET num = ? WHERE spname = ?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1, kuCunBySpName.getNum());
        preparedStatement.setString(2, kuCunBySpName.getSpName());

        int i = preparedStatement.executeUpdate();
        return i > 0;
    }
}
